package ar.uba.fi.tonyvaliente.documents;

import java.util.Iterator;

public class DocumentTermFilter extends DocumentFilter {
	
	private String term;

	public DocumentTermFilter(String term, boolean negated, DocumentHashing docHash,
			DocumentIndex index) {
		super(negated, docHash, index);
		this.term = term;
	}

	public String getTerm() {
		return term;
	}

	protected DocumentQueryResultIterator createResultIterator(int totalDocumentos, DocumentIndex index) {
		return new DocumentTermResultIterator(term, totalDocumentos, index);
	}
	
	/**
	 * Compara dos objetos de esta clase por termino
	 * y flag de negacion
	 * @param f un SignatureTermFilter cualquiera
	 * @return true si son iguales, false si no lo son.
	 */
	public boolean equals(DocumentTermFilter f) {
		return this.isNegated() == f.isNegated() && this.term.equals(f.term);
	}
	
	@Override
	public boolean equals(Object o) {
		if (o == this) return true;
		if (o == null) return false;
		if (!(o instanceof DocumentTermFilter)) return false;
		return equals((DocumentTermFilter)o);
	}
	
	@Override
	public int hashCode() {
		return (isNegated() + term).hashCode();
	}
	
	@Override
	public String toString() {
		if (isNegated()) {
			return "NOT " + term;
		} else {
			return term;
		}
	}

	private class DocumentTermResultIterator extends DocumentQueryResultIterator {

		private Iterator<Integer> idIterator;
		
		public DocumentTermResultIterator(String term, int totalDocumentos, DocumentIndex index) {
			super(totalDocumentos, index);
			this.idIterator = getDocumentIDsIterator(term);
		}

		public boolean hasNext() {
			return idIterator.hasNext();
		}

		public Integer next() {
			return idIterator.next();
		}

		private Iterator<Integer> getDocumentIDsIterator(String term) {
			return index.getDocuments(term).iterator();
		}
	}
}

